/*
 Xern Entity Relocation Network
 Copyright (C) 2010-2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include "Xern/PluginRegistrator.hpp"
#include "Xern/Entity.hpp"
#include "Xern/Engine.hpp"
#include "Xern/ResourceManager.hpp"
#include "BulletPhysics.hpp"
#include "PhysicRegion.hpp"
#include "RigidBody.hpp"
#include "BoxShape.hpp"
#include "CapsuleShape.hpp"
#include "CompoundShape.hpp"
#include "ConvexHullShape.hpp"
#include "SphereShape.hpp"
#include "ShapeLoader.hpp"

namespace XernBullet
{
	static PluginRegistrator<BulletPhysicsEngine>
	physicsEngine("Physics", "BulletPhysics");

	BulletPhysicsEngine::BulletPhysicsEngine()
	{
		broadphase = NULL;
		collisionConfiguration = NULL;
		dispatcher = NULL;
		dynamicsWorld = NULL;
		solver = NULL;
	}

	BulletPhysicsEngine::~BulletPhysicsEngine()
	{
		if(dynamicsWorld)
			Shutdown();
	}

	void BulletPhysicsEngine::Initialize()
	{
		if(dynamicsWorld)
			return;

		// Create the broadphase.
		broadphase = new btDbvtBroadphase();

		// Create the configuration.
		collisionConfiguration = new btDefaultCollisionConfiguration();
		dispatcher = new btCollisionDispatcher(collisionConfiguration);

		// Create the constraint solver.
		solver = new btSequentialImpulseConstraintSolver();

		// Create the dynamics world.
		dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);

		// Set the gravity.
		dynamicsWorld->setGravity(btVector3(0.0, -9.8, 0.0));

		// Create the shape loader.
		shapeLoader.reset(new ShapeLoader());
		Engine::Get().GetResourceManager()->RegisterResourceLoader(shapeLoader);
	}

	void BulletPhysicsEngine::Shutdown()
	{
		if(!dynamicsWorld)
			return;

		// Unregister the shape loader.
		Engine::Get().GetResourceManager()->UnregisterResourceLoader(shapeLoader);

		// Clean the physics engine.
		delete dynamicsWorld;
		delete solver;
		delete dispatcher;
		delete collisionConfiguration;
		delete broadphase;

		// Set the pointers to null.
		dynamicsWorld = NULL;
		solver = NULL;
		dispatcher = NULL;
		collisionConfiguration = NULL;
		broadphase = NULL;
	}

	bool BulletPhysicsEngine::Frame(float delta)
	{
		// Check that the world is created.
		if(!dynamicsWorld)
			return true;

		// Tell the world to run the simulation.
		dynamicsWorld->stepSimulation(delta);

		// Send touch event.
		int numManifolds = dynamicsWorld->getDispatcher()->getNumManifolds();
		for(int i = 0; i < numManifolds; i++)
		{
			btPersistentManifold *contactManifold = dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);
			btCollisionObject *obA = static_cast<btCollisionObject*> (contactManifold->getBody0());
			btCollisionObject *obB = static_cast<btCollisionObject*> (contactManifold->getBody1());

			if(!obA || !obB || contactManifold->getNumContacts() == 0)
				continue;

			RigidBody *bodyA = static_cast<RigidBody*> (obA->getUserPointer());
			RigidBody *bodyB = static_cast<RigidBody*> (obB->getUserPointer());
			if(!bodyA || !bodyB)
				continue;

			// Handle entity deletion in touch.
			boost::shared_ptr<Entity> entA = bodyA->GetTargetEntity();
			boost::shared_ptr<Entity> entB = bodyB->GetTargetEntity();
			if(!entA || !entB)
				continue;

			entA->OnTouch(entB);
			entB->OnTouch(entA);
		}
		return true;
	}

	btDynamicsWorld *BulletPhysicsEngine::GetWorld()
	{
		return dynamicsWorld;
	}

	boost::shared_ptr<IPhysicRegion> BulletPhysicsEngine::CreatePhysicRegion()
	{
		return boost::shared_ptr<IPhysicRegion> (new PhysicRegion(dynamicsWorld));
	}

	boost::shared_ptr<IRigidBody> BulletPhysicsEngine::CreateRigidBody(float mass, boost::shared_ptr<ICollisionShape> shape, boost::shared_ptr<Entity> target)
	{
		return boost::shared_ptr<IRigidBody> (new RigidBody(RigidBody::RBT_RIGIDBODY, mass, shape, target));
	}

	boost::shared_ptr<IRigidBody> BulletPhysicsEngine::CreateStaticBody(boost::shared_ptr<ICollisionShape> shape, boost::shared_ptr<Entity> target)
	{
		return boost::shared_ptr<IRigidBody> (new RigidBody(RigidBody::RBT_STATIC, 0.0f, shape, target));
	}

	boost::shared_ptr<IRigidBody> BulletPhysicsEngine::CreateDynamicBody(boost::shared_ptr<ICollisionShape> shape, boost::shared_ptr<Entity> target)
	{
		return boost::shared_ptr<IRigidBody> (new RigidBody(RigidBody::RBT_DYNAMIC, 0.0f, shape, target));
	}

	template<typename T>
	inline boost::shared_ptr<T> RegisterShape(boost::shared_ptr<T> shape)
	{
		Engine::Get().GetResourceManager()->RegisterExternalResource(shape);
		return shape;
	}

	boost::shared_ptr<IBoxShape> BulletPhysicsEngine::CreateBoxShape(const AABox &box)
	{
		return RegisterShape(CreateBoxShape((box.max-box.min)*0.5f));
	}

	boost::shared_ptr<IBoxShape> BulletPhysicsEngine::CreateBoxShape(const Vector3 &halfExtents)
	{
		return RegisterShape(boost::shared_ptr<IBoxShape> (new BoxShape(halfExtents)));
	}

	boost::shared_ptr<ICapsuleShape> BulletPhysicsEngine::CreateCapsuleShape(ICapsuleShape::CapsuleAxis axis, float radius, float height)
	{
		return RegisterShape(boost::shared_ptr<ICapsuleShape> (new CapsuleShape(axis, radius, height)));
	}

	boost::shared_ptr<ISphereShape> BulletPhysicsEngine::CreateSphereShape(float radius)
	{
		return RegisterShape(boost::shared_ptr<ISphereShape> (new SphereShape(radius)));
	}

	boost::shared_ptr<IConvexHullShape> BulletPhysicsEngine::CreateConvexHull(int numpoints, const Vector3 *points)
	{
		return RegisterShape(boost::shared_ptr<IConvexHullShape> (new ConvexHullShape(numpoints, points)));
	}

	boost::shared_ptr<IConvexHullShape> BulletPhysicsEngine::CreateConvexHull(int numplanes, const Plane *planes)
	{
		return RegisterShape(boost::shared_ptr<IConvexHullShape> (new ConvexHullShape(numplanes, planes)));
	}

	boost::shared_ptr<ICompoundShape> BulletPhysicsEngine::CreateCompoundShape()
	{
		return RegisterShape(boost::shared_ptr<ICompoundShape> (new CompoundShape()));
	}
};
